$(function(){

	// ajax
	(function(){

		var oldCash = '';
		var oldClick = '';
		var oldSpeed = 600;
		var detailDatas = []; // 详情队列
		var speed = 600;  // 每隔 n 秒下落一次。
		var total = 500000;
		var timer = null;

        clearInterval(timeTicket_all);
        var timeTicket_all = setInterval(function() {
           			getDate();
			getCateRank();
			getCityRank();
        }, 2 * 1000);

        clearInterval(timeTicket_detail);
                var timeTicket_detail = setInterval(function() {
			getDetail();
        }, 2 * 1000);



		// 今日累计
		function getDate(){
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/cpc/map/getMapDataTotal',
				async:false,
				success: function(data){
					// {time: 1431413178000, click_pv: 1669654, click_cash: 1360325.53}
					var date = new Date();

					date.setTime(data.time);
					console.log(data.time);
					var curDate = date.getFullYear() + '年' + toDouble((date.getMonth() + 1)) + '月' + toDouble(date.getDate()) + '日';
					var curTime = toDouble(date.getHours()) + ':' + toDouble(date.getMinutes()) + ':' + toDouble(date.getSeconds());
					var clickPv = data.click_pv;

					$('.cur_date').text(curDate);
					$('.cur_time').text(curTime);

					toUp($('.money_num'),oldCash,formatString(data.click_cash))
					toUp($('.click_num'),oldClick,format(data.click_pv))


					// 存上一次的数据
					oldCash = format(data.click_cash);
					oldClick = format(data.click_pv);

				},
				error: function(data){
					console.log('error:' + data);
				}
			});
		}

		// 类别排行
		function getCateRank(){
			$.ajax({
				type: 'post',
				data: {type:'CATE'},
				url: '/dashboard/realtime/cpc/map/getRanking',
				success: function(data){
					//{data: Array[10]} => {cash: 182841.63cate: "搬家"}  !! 前8
					if (data.data.length === 0) return;

					var curRank = data.data;
					if(data.data[0].cash > total){
						total += 200000;
						console.log(data.data[0].cash);
					} 

					$('.class_box  .name').each(function(i){
						$(this).text(data.data[i].cate);
					});
					$('.class_box  .amount').each(function(i){
						$(this).text(format(data.data[i].cash));
					});
					$('.class_box .bar i').each(function(i){
						var changeW = barChange($(this).attr('data-width'),parseFloat(data.data[i].cash/total) * 100 + '%');
						if(changeW){
							$(this).css('width',changeW);
							$(this).attr('data-width',changeW);
						}
					});

				},
				error: function(data){
					console.log('error:' + data);
				}

			});
		}

		// 城市排行
		function getCityRank(){
			$.ajax({
				type: 'post',
				data: {type:'CITY'},
				url: '/dashboard/realtime/cpc/map/getRanking',
				success: function(data){
					//{data: Array[10]} => {cash city}
					if (data.data.length === 0) return;

					if(data.data[0].cash > total){
						total += 200000;
						console.log(data.data[0].cash);
					} 
					var curRank = data.data;
					$('.city_box .name').each(function(i){
						$(this).text(data.data[i].city);
					});
					$('.city_box .amount').each(function(i){
						$(this).text(format(data.data[i].cash));
					});
					$('.city_box .bar i').each(function(i){
						var changeW = barChange($(this).attr('data-width'),parseFloat(data.data[i].cash/total) * 100 + '%');
						if(changeW){
							var _this = this;
							$(this)
							.css('width',changeW)
							.attr('data-width',changeW)
							.addClass('flash');
							setTimeout(function(){
								$(_this).removeClass('flash');
							},1000);
						}
					});
				},
				error: function(data){
					console.log('error:' + data);
				}

			});
		}

		// 详情
		// 存详情信息
		function getDetail(){
			if (speed != oldSpeed){
				clearInterval(timer);
				timer = setInterval(function(){
					toDown();
					oldSpeed = speed;
				},speed);
			};
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/cpc/map/getDetail',
				timeout : 2000,
				success: function(data){
					//{data: Array[10]} => {cash: 0cate: "合租房"city: "青岛"cost: 0.1platform: "M"time: 1431414881457userId: "16001679"}
					detailDatas = data.data;

					var len = data.data.length;
					if( len >= 145  ){
						speed = 100;
					}else if( len > 100){
						speed = 200;
					}else{
						speed = 300;
					}
				},
				error: function(data){
					console.log('error:' + data);
				}
			});
		}

		function toDown(){
			if(detailDatas.length === 0) return;
			var oneData = detailDatas.pop();

			var dom = $('<li></li>').html(function(){
				var date = new Date();

				date.setTime(oneData.time);

				var time =  toDouble(date.getHours()) + ':' + toDouble(date.getMinutes()) + ':' + toDouble(date.getSeconds());

				var html =  '<span>'+ time +'</span><span>' + oneData.userId + '</span><span>'+ oneData.city +'</span><span>' +
							oneData.cate +'</span><span>'+ oneData.platform +'</span><span>'+ oneData.cost +'</span>';
				return html;
			})
			// PC M APP
			var colors ;
			if(oneData.platform === 'PC'){
				colors = 'red'
			}else if(oneData.platform === 'M'){
				colors = 'gray'
			}else{
				colors = 'blue';
			}

			dom
			.addClass(colors)
			.prependTo('.click_box .box_data');

			setTimeout(function(){
				dom.remove();
			},8000);
		}

		// 变成2位数
		function toDouble(num){
			return parseInt(num,10) >= 10 ? '' + num : '0' + num;
		}

		// 每3数字加逗号
		function format(string){
			if (typeof string === 'number'){
				var str = parseInt(string,10) + '';
			}else if (typeof string === 'string'){
				var str = string;
			}

			var hearNum = str.length%3;
			var arr = [];

			if(hearNum != 0){
				arr.push(str.substr(0,hearNum));
			}

			for(var i = 1; i <= str.length/3;i++){
				arr.push(str.substr(hearNum + 3*(i-1),3));
			}

			return arr.join(',');
		}

		function formatString (x) {
	             x = (x + '').split('.');
                         return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (x.length > 1 ? '.' + x[1] : '');
		}

		// 改变bar长度
		function barChange(oldW,curW){
			if(!oldW) return curW;
			if(Math.abs(parseFloat(oldW,10) - parseFloat(curW,10)) < 0.02){
				return
			}else{
				return curW;
			}
		}

		// 向上滚动
		function toUp(dom,oldStr,curStr){


			// 第一次初始化 或 当长度变化时，改变布局
			if(!oldStr  || oldStr.length != curStr.length){
				dom.html(function(){
					var html = '';

					for(var i = 0; i < curStr.length; i++){
						html += '<p><span>'+curStr.charAt(i)
								+'</span><span>'+curStr.charAt(i)+'</span></p>'
					}

					return html;
				});

				setLayout(dom);
			}

			var len = Math.max(oldStr.length,curStr.length);

			for(var i = 0; i < len;i++){

				(function(index){
					var oldStrChar = oldStr.charAt(index);
					var curStrChar = curStr.charAt(index);

					if(oldStrChar != curStrChar){

						var duration = 400   // 运动时间
						var domP = dom.children().eq(index).children(); 
						var topNum = domP.first();	// 上面一排数值
						var btmNum = domP.last();	// 下面一排数值

						// 赋值新数据
						btmNum.text(curStrChar);

						topNum.animate({
							top:  '-64px'
						},duration,function(){
							//赋值新数值
							topNum.text(curStrChar);
							topNum.css('top',0);
						});

						btmNum.animate({
							top: 0
						},duration,function(){
							btmNum.css('top','64px');
						});
					}
				})(i);
			}
		}

		// 将浮动布局转换为绝对定位
		function setLayout(dom){

			// 先设置 top / left 
			dom.children().each(function(i){
				$(this).children().each(function(){
					$(this).css({
						top: $(this).position().top,
						left: $(this).position().left
					});
				});
			});

			// 再进行绝对定位，保证所有元素都在正确位置
			dom.children().each(function(){
				$(this).children().each(function(){
					$(this).css({
						position: 'absolute'
					});
				});
			});
		}

	})();

});